﻿using System;
using System.Collections.Generic;
using System.Linq;
using cludg.Repository.NHibernate.Sessions;
using NHibernate;
using NHibernate.Linq;

namespace cludg.Repository.Content.NHibernate
{
	using Domain.Content;

	public class ContentRepository<TContent> : IContentRepository<TContent> where TContent : class, IContent
	{
		protected readonly INHibernateSessionController SessionController;

		public ContentRepository(INHibernateSessionController sessionController)
		{
			SessionController = sessionController;
		}

		public IQueryable<TContent> Get()
		{
			return SessionController.Current.Linq<TContent>(
				SessionController.Current.CreateCriteria<TContent>().SetCacheable(true));
		}

		public TContent ById(string id)
		{
			return SessionController.Current.Get<TContent>(id);
		}


		public string Add(TContent content)
		{
			try
			{
				SessionController.Current.Save(content);
				return content.Id;
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}

		public void Delete(string contentId)
		{
			var obj = SessionController.Current.Get<TContent>(contentId);
			if (obj != null)
			{
				try
				{
					SessionController.Current.Delete(obj);
				}
				catch (Exception)
				{
					SessionController.Reset();
					throw;
				}
			}
		}

		public void Save(TContent content)
		{
			try
			{
				SessionController.Current.Update(content);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}
	}
}
